package cfca.paperless.client.servlet._1_basic._1_06_CompoundSealAutoPdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.ChannelBean;
import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.bean.PdfBean;
import cfca.paperless.client.bean.SealUserInfo;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.Base64;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;

/**
 * @Description PDF自动化复合签章接口，使用示例。
 * 1，操作对象为本地待处理的单个PDF文件。
 * 2，使用服务端管理页面中预先制作的普通企业印章进行签章。
 * 3，签署多个场景证书印章。
 * 4，签署1个普通企业印章。
 * 5，签章类型支持4种，1=空白标签签章,2=坐标签章,3=关键字签章，4=位置标识。
 * 6，返回成功签章的PDF文件。
 * 
 * @Author dell
 * @Date 2016-5-13
 * @CodeReviewer TODO
 */
public class CompoundSealAutoPdfTest06 {

    public static void main(String[] args) throws Exception {

        try {
            PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.url, 10000, 60000);

///////////////////////////如下为用户1的数据，如果没用用户1此处可以省略/////////////////////////////////////////////////
            String pngFilePath = "./TestData/zhangfei.png";
            
            String pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
            if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
                throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
            }
            byte[] handwritingImage1 = FileUtils.readFileToByteArray(new File(pngFilePath));
            byte[] handwritingData1 = handwritingImage1;
            
            pngFilePath = "./TestData/1.png";
            pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
            if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
                throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
            }
            byte[] identificationFrontData = FileUtils.readFileToByteArray(new File(pngFilePath));
            
            pngFilePath = "./TestData/2.png";
            pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
            if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
                throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
            }
            byte[] identificationBackData = FileUtils.readFileToByteArray(new File(pngFilePath));
            List<MultiDataBean> list1 = new ArrayList<MultiDataBean>();
            list1.add(new MultiDataBean(handwritingData1, "handwritingData.dat", "media-id", "0"));//手写签名数据
            list1.add(new MultiDataBean(handwritingImage1, "handwritingImage.png", "2"));//手写签名图片
            list1.add(new MultiDataBean(identificationFrontData, "identificationFrontImage.png", "2"));//身份证正面
            list1.add(new MultiDataBean(identificationBackData, "identificationBackImage.png", "2"));//身份证反面
            //list1.add(new MultiDataBean(video, "video.mp4", "2"));
            String[] proofHashAndMultiData1 = PaperlessUtil.getProofHashAndMultiData(list1);

            SignLocation signLocation = new SignLocation("代理人签名", "R", 30, 0);
//            SignLocation signLocation2 = new SignLocation("代理人签名", "R", 10, 0);
            List<SignLocation> signLocationList = new ArrayList<SignLocation>();
//            signLocationList.add(signLocation2);
            signLocationList.add(signLocation);signLocation.setPage(1);
            SealUserInfo sealUserInfo = new SealUserInfo("张飞", "Z", "0003aa22215", "15744659823", "北京", "签合同");
            sealUserInfo.setKeyAlg("SM2");
            String proofSealStrategyXml1 = StrategyUtil.createProofSealStrategyXml(handwritingImage1, sealUserInfo, signLocationList, proofHashAndMultiData1[0]);
///////////////////////////以上为用户1的数据/////////////////////////////////////////////////
///////////////////////////如下为用户2的数据，如果没用用户2此处也可以省略/////////////////////////////////////////////////
            byte[] handwritingImage2 = FileUtils.readFileToByteArray(new File("./TestData/zhangfei.png"));
            byte[] handwritingData2 = handwritingImage2;
            List<MultiDataBean> list2 = new ArrayList<MultiDataBean>();
            list2.add(new MultiDataBean(handwritingData2, "handwritingData.dat", "2"));
            list2.add(new MultiDataBean(handwritingImage2, "handwritingImage.png", "2"));
            String proofHashAndMultiData2[] = PaperlessUtil.getProofHashAndMultiData(list2);

            signLocation = new SignLocation(1, "代理人签名", "D", 10, 0);signLocation.setPage(2);
            sealUserInfo = new SealUserInfo("张飞2", "Z", "0003aa222156", "15488965698", "北京", "签合同");
            sealUserInfo.setKeyAlg("SM2");
            String proofSealStrategyXml2 = StrategyUtil.createProofSealStrategyXml(handwritingImage2, sealUserInfo, signLocation, proofHashAndMultiData2[0]);
            // ///////////////////////////////////////////////////////
            ///////////////////////////以上为用户2的数据/////////////////////////////////////////////////

            ///////////////////////////如下为加盖机构印章的策略/////////////////////////////////////////////////
            signLocation = new SignLocation(1, "银行签章", "D", 20, 20);
            sealUserInfo = new SealUserInfo("张三五", "北京", "签合同");
            String sealCode = "org001";
            String sealPassword = "11111111";

            String businessCode = "";
            String businessCodeStyle = "font-size:19;x-ratio:0.1;y-ratio:0.5";
            sealUserInfo.setBusinessCode(businessCode);
            sealUserInfo.setBusinessCodeStyle(businessCodeStyle);
            
            // 设置印章显示大小，可以不设置。比如：100，代表100px。比如需要把章显示为4cm（圆章且DPI为96）时，传入151即可。（并且imageScale配置为0.87）
            //sealUserInfo.setSealImageSize(100);
            
            
            String sealStrategyXml = StrategyUtil.createSealStrategyXml(sealCode, sealPassword, sealUserInfo, signLocation);
//            sealStrategyXml = StrategyUtil.createSealStrategyXml(sealCode, sealPassword, handwritingImage1, sealUserInfo, signLocation);

            byte[] pdfFile = FileUtils.readFileToByteArray(new File("./TestData/file.pdf"));
            String savedPdfId = GUID.generateId();
            String compoundSealStrategyXml = "<List>" + proofSealStrategyXml1 + proofSealStrategyXml2 + sealStrategyXml + "</List>";
            String outputFilePath = "auto";
//            outputFilePath = "/clsu/pdf/pdf2/" + savedPdfId + ".pdf";
            String multiData = "[" + proofHashAndMultiData1[1] + "," + proofHashAndMultiData2[1] + "]";
//            multiData = "";
            String bizSerialNo = "";//GUID.generateId();
            String bizTypeCode = "B001";
            PdfBean pdfBean = new PdfBean(Base64.toBase64String(pdfFile), savedPdfId, bizSerialNo, bizTypeCode, outputFilePath, "6227000015894784559");
//            pdfBean = new PdfBean(Base64.toBase64String(pdfFile), bizSerialNo, bizTypeCode, outputFilePath);
            pdfBean.setPdfOwnerPassword(Base64.toBase64String("123456".getBytes()));
            pdfBean.setReturnPdfOrNot(false);//可以指定不返回pdf,默认返回pdf
            String pdfBeanXml = PaperlessUtil.buildPdfBeanXml(pdfBean);
            long start = System.currentTimeMillis();
            String channelBeanXml = new ChannelBean(PaperlessConfig.channelCode).toString();
            
            // 获取场景证书的方式，与证据证书签章策略文件配合使用。默认值为0。0：实时从CFCA CA服务申请下载场景证书；1：使用从CFCA CA服务预先申请下载并存储在本地的场景证书；
            String sceneCertChannel = "0";
            
            // 获取时间戳的方式。默认值为0。0：实时访问CFCA 时间戳服务；1：使用从CFCA购置并在本地部署的时间戳服务器产品；
            String timestampChannel = "0";
            
           
            String systemNo = GUID.generateId();
            byte[] sealedPdf = clientBean.compoundSealAutoPdf(systemNo,pdfBeanXml, multiData, compoundSealStrategyXml, PaperlessConfig.operatorCode, channelBeanXml, sceneCertChannel, timestampChannel);

            System.out.println(sealedPdf.length);
            String errorRsString = PaperlessUtil.isError(sealedPdf);
            if ("".equals(errorRsString)) {
                if (pdfBean.isReturnPdfOrNot()) {
                    IoUtil.write("./TestData/output/compoundSealAutoPdf.pdf", sealedPdf);
                } else {
                    System.out.println(new String(sealedPdf, "UTF-8"));
                }
            } else {
                System.out.println(new String(sealedPdf, "UTF-8"));
            }
            System.out.println("########## compoundSealAutoPdf" + " end,time:" + (System.currentTimeMillis() - start) + "##########");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
